<template>
  <div class="process-view">
    <div class="page-header">
      <h1>进程监控</h1>
      <p>实时监控系统进程运行状态</p>
    </div>

    <!-- 进程类型选择器 -->
    <div class="process-filter">
      <el-radio-group v-model="selectedType" @change="handleTypeChange">
        <el-radio-button label="all">全部进程</el-radio-button>
        <el-radio-button label="java">Java进程</el-radio-button>
        <el-radio-button label="python">Python进程</el-radio-button>
        <el-radio-button label="cpp">C++进程</el-radio-button>
        <el-radio-button label="port">网络进程</el-radio-button>
      </el-radio-group>
      <el-button @click="refreshProcesses" :loading="loading" type="primary" class="refresh-btn">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 进程统计信息 -->
    <div class="process-stats">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ processStats.total }}</div>
              <div class="stat-label">总进程数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ processStats.java }}</div>
              <div class="stat-label">Java进程</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ processStats.python }}</div>
              <div class="stat-label">Python进程</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">{{ processStats.others }}</div>
              <div class="stat-label">其他进程</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 进程列表 -->
    <div class="process-list">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>进程列表</span>
            <el-tag type="info">{{ processes.length }} 个进程</el-tag>
          </div>
        </template>
        
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else-if="processes.length === 0" class="empty-container">
          <el-empty description="暂无进程数据" />
        </div>
        
        <div v-else class="process-table">
          <el-table :data="processes" stripe style="width: 100%">
            <el-table-column prop="pid" label="PID" width="80" />
            <el-table-column prop="name" label="进程名称" min-width="150">
              <template #default="{ row }">
                <div class="process-name">
                  <span class="name-text">{{ row.name || 'Unknown' }}</span>
                  <el-tag 
                    v-if="getProcessType(row.name)" 
                    :type="getProcessTypeColor(getProcessType(row.name))" 
                    size="small"
                  >
                    {{ getProcessType(row.name) }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="cpuUsage" label="CPU使用率" width="120">
              <template #default="{ row }">
                <div class="cpu-usage">
                  <el-progress 
                    :percentage="Math.min(row.cpuUsage || 0, 100)" 
                    :color="getCpuProgressColor(row.cpuUsage)"
                    :show-text="false"
                    :stroke-width="8"
                  />
                  <span class="cpu-text">{{ (row.cpuUsage || 0).toFixed(1) }}%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="memoryUsage" label="内存占用" width="120">
              <template #default="{ row }">
                <span class="memory-usage">{{ formatMemory(row.memoryUsage) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="upTime" label="运行时间" width="120">
              <template #default="{ row }">
                <span class="uptime">{{ formatUptime(row.upTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="commandLine" label="命令行" min-width="200">
              <template #default="{ row }">
                <el-tooltip :content="row.commandLine || 'N/A'" placement="top">
                  <span class="command-line">{{ truncateText(row.commandLine, 50) }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="killProcess(row.pid)">
                  结束
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import request_lm from "../utils/request_lm.js"

const selectedType = ref('all')
const processes = ref([])
const loading = ref(false)

// 进程统计
const processStats = computed(() => {
  const stats = {
    total: processes.value.length,
    java: 0,
    python: 0,
    others: 0
  }
  
  processes.value.forEach(process => {
    const type = getProcessType(process.name)
    if (type === 'Java') stats.java++
    else if (type === 'Python') stats.python++
    else stats.others++
  })
  
  return stats
})

// 获取进程类型
const getProcessType = (processName) => {
  if (!processName) return null
  
  const name = processName.toLowerCase()
  if (name.includes('java')) return 'Java'
  if (name.includes('python') || name.includes('py.exe')) return 'Python'
  if (name.includes('nginx') || name.includes('apache') || name.includes('mysql')) return 'Server'
  if (name.endsWith('.exe')) return 'C++'
  return 'Other'
}

// 获取进程类型颜色
const getProcessTypeColor = (type) => {
  const colors = {
    'Java': 'success',
    'Python': 'warning', 
    'Server': 'info',
    'C++': 'primary',
    'Other': 'default'
  }
  return colors[type] || 'default'
}

// 获取CPU进度条颜色
const getCpuProgressColor = (percentage) => {
  if (percentage >= 80) return '#f56c6c'
  if (percentage >= 50) return '#e6a23c'
  return '#67c23a'
}

// 格式化内存大小
const formatMemory = (bytes) => {
  if (!bytes) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let size = bytes
  let unitIndex = 0
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`
}

// 格式化运行时间
const formatUptime = (uptime) => {
  if (!uptime) return '0s'
  
  const seconds = Math.floor(uptime / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  
  if (days > 0) return `${days}d ${hours % 24}h`
  if (hours > 0) return `${hours}h ${minutes % 60}m`
  if (minutes > 0) return `${minutes}m ${seconds % 60}s`
  return `${seconds}s`
}

// 截断文本
const truncateText = (text, maxLength) => {
  if (!text) return 'N/A'
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 处理类型变化
const handleTypeChange = () => {
  fetchProcesses()
}

// 刷新进程列表
const refreshProcesses = () => {
  fetchProcesses()
}

// 获取进程列表
const fetchProcesses = async () => {
  try {
    loading.value = true
    let response
    
    if (selectedType.value === 'all') {
      response = await request_lm.get('/processes')
    } else {
      response = await request_lm.get(`/processes/${selectedType.value}`)
    }
    
    processes.value = response.data || []
    console.log('进程数据:', processes.value)
  } catch (error) {
    console.error('获取进程信息失败:', error)
    processes.value = []
  } finally {
    loading.value = false
  }
}

// 结束进程
const killProcess = (pid) => {
  // 这里可以添加结束进程的逻辑
  console.log('结束进程:', pid)
  // 注意：实际应用中需要后端支持进程结束功能
}

onMounted(() => {
  fetchProcesses()
})
</script>

<style scoped lang="scss">
.process-view {
  width: 100%;
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
  
  h1 {
    color: #303133;
    font-size: 28px;
    font-weight: 600;
    margin: 0 0 8px 0;
  }
  
  p {
    color: #909399;
    font-size: 14px;
    margin: 0;
  }
}

.process-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  
  .refresh-btn {
    margin-left: 16px;
  }
}

.process-stats {
  margin-bottom: 20px;
  
  .stat-card {
    text-align: center;
    border: none;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .stat-content {
      padding: 16px;
      
      .stat-value {
        font-size: 24px;
        font-weight: 600;
        color: #409eff;
        margin-bottom: 8px;
      }
      
      .stat-label {
        font-size: 14px;
        color: #606266;
      }
    }
  }
}

.process-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    color: #303133;
  }
  
  .loading-container {
    padding: 20px;
  }
  
  .empty-container {
    padding: 40px;
  }
  
  .process-table {
    .process-name {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .name-text {
        font-weight: 500;
        color: #303133;
      }
    }
    
    .cpu-usage {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .cpu-text {
        font-size: 12px;
        color: #606266;
        min-width: 40px;
      }
    }
    
    .memory-usage {
      font-family: 'Courier New', monospace;
      font-size: 12px;
      color: #606266;
    }
    
    .uptime {
      font-size: 12px;
      color: #606266;
    }
    
    .command-line {
      font-family: 'Courier New', monospace;
      font-size: 11px;
      color: #909399;
      cursor: pointer;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .process-view {
    padding: 16px;
  }
  
  .process-filter {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    
    .refresh-btn {
      margin-left: 0;
    }
  }
  
  .process-stats .el-col {
    margin-bottom: 16px;
  }
}
</style>